<?php
class doom_log_file {

    public $_config;

    public $_logFile;
    
    public $error;

    public function __construct($config) {
        $this->_config = $config;
        $this->error = new doom_core_error();
        //         register_shutdown_function(array(&$this, 'close'));
    }

    public function debug($message) {
        fwrite($this->getLogFile(), $message, $this->_config['lineLength']);
    }

    public function error($message) {
        fwrite($this->getLogFile(), $message, $this->_config['lineLength']);
    }
    
    public function getLogFile() {
        if ($this->_logFile == null) {
            $this->_logFile = doom_log_filemgr::get($this->_config);
        }
        return $this->_logFile;
    }
}

class doom_log_filemgr {
    
    static public $error;
    
    public static $logFiles = array();
    
    static public function _static_construct() {
        self::$error = new doom_core_error();
    }
    
    static public function get($fn) {
        $logKey = md5($fn);
        
        $logFile = self::$logFiles[$logKey];
        if ($logFile == NULL) {
            $logFile = fopen($fn, 'a');
            if ($logFile === false) {
                self::$error->set(-1 , "Error open file: $fn");
                return FALSE;
            }
            self::$logFiles[$logKey] = $logFile;
    
        }
        return $logFile;
    }
    
    /**
     * 关闭数据库连接
     * @param array/resource $conn 数据库配置/连接resource
     */
    static public function close($fn) {
    
        if (is_string(fn)) {
            $logKey = md5($fn);
            if (($logFile = self::$logFiles[$logKey]) != NULL && is_resource($logFile)) {
    
                if (fclose($logFile)) {
                    unset(self::$logFiles[$connKey]);
                    return TRUE;
                } else {
                    return FALSE;
                }
            } else {
                return TRUE;
            }
        } else if (is_resource($fn)) {
            $logKey = array_search($fn, self::$logFiles);
            if (fclose($fn)) {
                unset(self::$logFiles[$logKey]);
                return TRUE;
            } else {
                return FALSE;
            }
        } else {
            return FALSE;
        }
    }
    
    /**
     * 关闭所有连接
     */
    static public function closeAll() {
    
        foreach (self::$logFiles as $logKey => $logFile) {
            if (is_resource($logFile)) {
                if (fclose($connection)) {
                    unset(self::$logFiles[$logKey]);
                }
            }
        }
    }
}
?>